// pages/shopDetail/shopDetail.js
import {
  requestUtil,
  getbaseUrl
} from "../../utils/request"

import {
  dateConversion
} from "../../utils/util"

const io  = require('../../utils/weapp.socket.io')

let news = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId: "",
    orderId: "",
    shopData: {},
    cartList: [],
    totalPrice: 0,
    shopNum: 0,
    baseUrl: '',
    orderNo: "",
    disRmb: 0,
    // 用户的信息
    userInfo: {},
    show: false,
    passError: "",
    money: 0,
    comment:0,
  },

  toback() {
    wx.navigateBack({
      delta: 0,
    })
  },

  // 取消支付或确认支付
  cancel(e) {
    let active = e.currentTarget.dataset.active
    let orderNo = this.data.orderNo
    let orderDate = dateConversion(new Date())
    wx.showModal({
      title: "取消订单",
      content: "订单取消后，需要新选择商品下单",
      success: (res) => {
        if (res.confirm) {
          let res = requestUtil({
            url: '/shop/changeOrderActive',
            data: {
              active,
              orderNo,
              orderDate
            },
            method: "get"
          })

          res.then(({
            data
          }) => {
            if (data.status == 200) {
              // console.log("fesfes")
              wx.navigateBack({
                delta: 1,
              })
            } else {

            }
          })
        } else {

        }
      }
    })
  },

  // 取消支付
  cancelPay() {
  
    wx.showToast({
      title: '用户取消了支付',
    })
  },

  // 退单
  chargeback(){
    let orderNo = this.data.shopData.orderNo
    let orderDate = dateConversion(new Date())

    let totalPrice = this.data.totalPrice-this.data.disRmb
    // let disRmb = this.data.disRmb
    let active = 5
    let openId = this.data.openId

   wx.showModal({
    //  cancelColor: 'cancelColor',
     title:"商品退款",
     content:"是否真的退款，退款成功后金额会原路返回",
     success:(res)=>{
        if(res.confirm){
          let res = requestUtil({
            url: '/shop/changeOrderActive',
            data: {
              active,
              orderNo,
              orderDate
            },
            method: "get"
          })    
      
          res.then(({data})=>{
            if(data.status==200){
              wx.showToast({
                title: '申请退款成功',
              })
              this.deduction(openId,totalPrice)
            
              wx.navigateBack({
                delta: 1,
              })
            }else{
              wx.showToast({
                title: '申请退款失败',
              })
            }
          })
        }
        if(res.cancel){
          wx.showToast({
            title: '用户取消退款',
          })
        }

     }
   })

    // console.log(orderId,openId,totalPrice-disRmb)

  },


   // 狗扣钱
   deduction(openId,totalPrice){
    let disRmb  = this.data.disRmb
    // console.log(totalPrice-disRmb)
    // console.log(totalPrice,disRmb)
      requestUtil({
        url:"/shop/noMatchPassword",
        method:"get",
        data:{
          openId,
          money:totalPrice
        }
      })
  },

  // 跳到评论页
  toComment(){
    if(this.data.comment==2)return
    let shopId = this.data.shopData.id
    let orderId = this.data.orderId
    wx.navigateTo({
      url: `/pages/comment/comment?orderId=${orderId}&shopId=${shopId}`,
    })
  },

  // 创建socket.io通信
  received(){
    let openId = this.data.userInfo.openid?this.data.userInfo.openid:''

    let baseUrl = getbaseUrl()
    news = io(baseUrl)
    news.on('connect',(res)=>{
        console.log('connection created.')
    })

    news.on(`${openId}`,(data)=>{
      console.log("监听到了")
      this.getOneData()
  })
  },

  // 支付时的回调
  submit(e) {
    let totalPrice = -(this.data.totalPrice-this.data.disRmb)
    let money = this.data.money
    // let disRmb  = this.data.disRmb
    // console.log(totalPrice,money)
    let boolean = parseFloat(totalPrice) > parseFloat(money)
    if (boolean) {
      console.log(totalPrice,money,boolean)
      this.setData({
        passError: "账户余额不足"
      })
      return
    }
    let active = 1
    let orderNo = this.data.orderNo
    let orderDate = dateConversion(new Date())

    // 检索密码是否正确
    let openId = this.data.userInfo.openid
    let password = e.detail.value

    let res = requestUtil({
      url: "/shop/matchPassword",
      method: "get",
      data: {
        password,
        openId
      }
    })
    res.then(({data}) => {
        // console.log(data)
        // 如果等一就是密码正确
        if (data.data == 1) {
          let res = requestUtil({
            url: '/shop/changeOrderActive',
            data: {
              active,
              orderNo,
              orderDate
            },
            method: "get"
          })

          res.then(({data}) => {
            if (data.status == 200) {
              news.emit("pay",'用户支付了')
              this.deduction(openId,totalPrice)
              this.setData({
                passError: ""
              })
              this.getOneData()
              this.setData({
                show: false
              })
              // wx.navigateBack({
              //   delta: 1,
              // })
            }
          })
          }

          if (data.data == 0) {
            this.setData({passError: "密码错误，请重试?"})
          }

        })

    
},

// 确认支付
pay(e) {
    let active = e.currentTarget.dataset.active
    let orderNo = this.data.orderNo
    let orderDate = dateConversion(new Date())
    // let  mealCode = "1"+Math.ceil(Math.random()*(1000-1)+1)

    this.setData({
      show: true
    })
    // wx.showModal({
    //   title: "请输入密码",
    //   content: "蛋糕店",
    //   success: (res) => {
    //     if (res.confirm) {
    //       let res = requestUtil({
    //         url: '/shop/changeOrderActive',
    //         data: {
    //           active,
    //           orderNo,
    //           orderDate
    //         },
    //         method: "get"
    //       })

    //       res.then(({
    //         data
    //       }) => {
    //         if (data.status == 200) {
    //           wx.navigateBack({
    //             delta: 1,
    //           })
    //         }
    //       })
    //     }else{
    //       wx.showToast({
    //         title: '用户取消支付',
    //       })
    //     }
    //   }
    // })
  },

  // 获取用户的金额
  getUserMoney() {
    let openId = this.data.openId
    let res = requestUtil({
      url: "/shop/getUserMoney",
      method: "get",
      data: {
        openId
      }
    })
    res.then(({
      data
    }) => {
      // console.log(data)
      let totalPrice = data.data.reduce((total, item) => {
        return total += item.money
      }, 0)
      if (data.status == 200) {
        this.setData({
          money: totalPrice.toFixed(2)
        })
      } else {
        this.setData({
          money: 0
        })
      }
    })
  },

  // 购物车数组
  cartList(arr) {
    let shopNum = arr[0].orderList.length
    let totalPrice = parseFloat(arr[0].orderList.reduce((total, item) => {
      return total += item.num * item.price
    }, 0).toFixed(2))

    this.setData({
      cartList: arr[0].orderList,
      shopNum,
      totalPrice: totalPrice.toFixed(2)
    })
  },

  // 获取单条数据
  getOneData() {
    let res = requestUtil({
      url: "/shop/getOneOrder",
      method: "get",
      data: {
        orderNo: this.data.orderNo,
        openId: this.data.openId
      }
    })
    res.then(({
      data
    }) => {
      let disRmb = 0

      this.cartList(data.data)
      if (data.data[0].shopDiscount.length > 0) {
        disRmb = data.data[0].shopDiscount[0].disRmb
      } else {
        disRmb = 0
      }
      // let disRmb = data.data[0].disRmb?data.data[0].disRmb:0
      // console.log(data.data)
      this.setData({
        shopData: data.data[0],
        disRmb,
        baseUrl: getbaseUrl() + "/image/"
      })
    })
  },

  // 获取本地的用户信息

  getUserInfo() {
    wx.getStorage({
      key: "userInfo",
      success: (res) => {
        // res.data
        this.setData({
          userInfo: JSON.parse(res.data)
        })
        this.getUserMoney()
      },
      fail: () => {
        this.setData({
          userInfo: {}
        })
      }

    })
  },

  // 保存评论状态
  storeStatus(orderId){
    wx.setStorage({
      key:orderId,
      data:1,
      success:()=>{
        wx.getStorage({
          key: orderId,
          success:(res)=>{
           this.setData({
            comment:res.data
           })
          }
        })
      }
    })
  },

  // 获取本地的评论状态
  getStreoCommentStatus(orderId){
      wx.getStorage({
        key: orderId,
        success:(res)=>{
        this.setData({
          comment:res.data
        })
        },
        fail:()=>{
          this.storeStatus(orderId)
        }
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    if (options) {
      // console.log(options)
      let orderId =options.orderId
      this.setData({
        orderId: options.orderId,
        openId: options.openId,
        orderNo: options.orderno,
      })
      this.getStreoCommentStatus(orderId)
      this.getOneData()
    }
    this.getUserInfo()
   setTimeout(()=>{
    this.received()
   },50)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let orderId = this.data.orderId
    if(orderId){
      wx.getStorage({
        key: orderId,
        success:(res)=>{
         this.setData({
          comment:res.data
         })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
      news.disconnect()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    news.disconnect()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})